import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import download from '@/utils/download';
import dataTime from '../../../utils/dataTime';
import { FormattedMessage } from 'umi-plugin-react/locale';
import Relevance from '../../../modules/popoutRelevance';
import UpDownCharacter from '../../../modules/UpDownCharacter';
import { Row, Col, Card, Icon, Table, Form, Spin, Modal, Button, message, Tabs, DatePicker, Select, Input, Tooltip, Drawer, } from 'antd';
import styles from "./index.less";
import EditQa from '../../KnowledgeManagement/Overview/editQa';
const TabPane = Tabs.TabPane
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const Option = Select.Option;
const Search = Input.Search;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_8lpmy5tq6hn.js', // 在 iconfont.cn 上生成
});
@connect(({ process, loading }) => ({
  process,
  loading: loading.effects['waitingLearningIssue/fetch'],
}))

class UnknownProblem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loginjqr: false,
      logins: true,
      qaListTable: [],
      total2: '',
      knowledgeList: [],
      upDownDate: [],
      total: '',
      beginTime: '',
      overTime: '',
      total: '',
      login: false,
      dataSource: [],
      pageSize: 15,
      page: 1,
      selectedRowKeys: [],
      electa: 'time',
      electb: 'false',
      portJudge: true,
      break: false,
      field: 'q',
      question: '',
      evaluate: '',
      ignored: false,
      order: 'updateTime',
      asc: 'desc',
      zuid: '',
      shutRelevance: false,
      showModel1: false,
      numberRadio: '1',
      pageSizetwo: 10,
      pagetwo: 1,
      nodeId: '',
      nodeIdName: '所有分类',
      close: false,
      qaId: "",
      isUpdate: false,
      aALeng: '',
      glLeng: 10,
    };
  }

  componentWillMount() {
    let sysTime = dataTime.formatDate(new Date().getTime()); // 初始时间
    let toTime = moment().subtract('days', 7).format('YYYY/MM/DD');
    this.setState({
      beginTime: toTime.replace(/\//g, '-'),
      overTime: sysTime.replace(/\//g, '-'),
    });
  }

  // eslint-disable-next-line react/sort-comp
  fetch = (query, ignored, from, to, page, limit, order, sort) => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'waitingLearningIssue/fetchr',
        payload: { query, ignored, from, to, page, limit, order, sort },
        callback: res => {
          let temp = res.list;
          temp.map((item, index) => {
            item['key'] = index
            item['time'] = Number(item.updateTime)
          });
          this.props.totalc(Number(res.total));
          this.setState({ dataSource: temp, selectedRowKeys: [], total: Number(res.total), selectedRows: null, login: false, logins: true, })
        },
      });
    });
  }

  getFtch() {
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
    this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
  }

  componentDidMount() {
    // this.fetch()
    this.props.onRef(this);
  }

  upDate = (id) => {
    this.setState({ loginjqr: true });
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'waitingLearningIssue/fetchd',
      payload: { statChatId: id },
      callback: res => {
        if (res.list) {
          this.setState({ upDownDate: res.list, loginjqr: false })
        } else {
          this.setState({ upDownDate: [1], loginjqr: false })
        }
      },
    });
  }

  // 上下文组件回调函数
  handleSubUpDwonDate = (val) => {
    setTimeout(() => {
      this.upDate(val.lastChatId)
    }, 1)
  }

  // 获取关联列表数据
  AnswerRelevance = (question, field, query, page = 1, pageSize = 10) => {
    this.setState({ logins: true });
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'waitingLearningIssue/fetchz',
      payload: { robotId: currentUser.robotId, question, field, query, page, limit: pageSize },
      callback: res => {
        let aA = res.suggestList;
        let bB = res.qaList;
        let aALeng = res.suggestList.length;
        let bBLeng = res.qaList.length;
        const total = [...aA, ...bB];
        total.map((item, index) => {
          item['key'] = index;
          item['time'] = Number(item.updateTime);
        });
        this.setState({ total2: Number(res.total), qaListTable: total, logins: false, aALeng: aALeng, glLeng: Number(aALeng + bBLeng), })
      },
    });
  }

  // 搜索内容
  onFrom = (val) => {
    this.setState({ pagetwo: 1, query: val }, () => {
      if (val === '') {
        this.AnswerRelevance(this.state.question, this.state.field, this.state.query, 1, this.state.glLeng)
      } else {
        this.AnswerRelevance(val, this.state.field, this.state.query, 1, this.state.glLeng)
      }
    })
  }

  // 搜索问题
  onFromA = (val) => {
    let text;
    if (val === '1') {
      text = 'q'
    };
    if (val === '2') {
      text = 'a'
    };
    this.setState({ pagetwo: 1, field: text });
    setTimeout(() => {
      this.AnswerRelevance(this.state.question, this.state.field, this.state.query, 1, this.state.glLeng)
    })
  }

  handleSubmitComment = (current) => {
    this.setState({ pagetwo: current });
    this.AnswerRelevance(this.state.question, this.state.field, this.state.query, current, this.state.glLeng);
  }

  down = () => {
    const { dispatch } = this.props;
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
    let userInfo = this.props.form.getFieldsValue();// 获取数据
    const data = { from: beginTime, ignored: userInfo.lose, order: order, sort: asc, to: overTime, query: userInfo.seek };
    dispatch({
      type: 'waitingLearningIssue/dcexportRg',
      payload: data,
      callback: (res) => {
        let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
        download.byBlob(res.fileBlob, filename);
      }
    });
  }

  callback = (key) => {

  }

  // 日期选择｛开始日期——结束日期｝
  onChange = (date, dateString) => {
    if (date && dateString) {
      this.setState({
        beginTime: dateString[0].replace(/\//g, '-'),
        overTime: dateString[1].replace(/\//g, '-'),
      });
    } else {
      message.error(`请输入开始至结束日期`)
    }
  };

  // 查看
  handleSubmit = () => {
    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    // let usercz = this.props.form.resetFields();   // 重置表单数据
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({ seek: userInfo.seek, })
        let a = '';
        if (userInfo.lose === 'true') {
          a = true;
          this.setState({ electb: 'true', portJudge: false, break: true, page: 1 }, () => {
            const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
            this.fetch(seek, true, beginTime, overTime, page, pageSize, order, asc);
          })
        } else if (userInfo.lose === 'false') {
          a = false;
          this.setState({ electb: 'false', portJudge: true, break: false, page: 1 }, () => {
            const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
            this.fetch(seek, false, beginTime, overTime, page, pageSize, order, asc);
          })
        }
      }
    })
  }

  newlyAdded = (row) => {
    this.setState({ qaId: Array(row.question.replace(/<.*?>/g, "")), }, () => {
      this.setState({ close: true })
    })
  }

  onClose = () => {
    this.setState({ close: false, }, () => {
      const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
      this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
    });
  };

  ignore = (row) => {
    let its = [];
    its.push(row.id);
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'waitingLearningIssue/fetchk',
        payload: { ids: its, ignored: this.state.portJudge },
        callback: res => {
          if (res.code == 200) {
            message['success'](`${res.msg}`);
            setTimeout(() => {
              const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
              this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
            }, 1)
          }
        },
      });
    });
  }

  recovery = (row) => {
    let its = [];
    its.push(row.id);
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'waitingLearningIssue/fetchk',
        payload: { ids: its, ignored: this.state.portJudge },
        callback: res => {
          if (res.code == 200) {
            message['success'](`${res.msg}`);
            setTimeout(() => {
              const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
              this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
            }, 1)
          }
        },
      });
    });
  }

  handleDelete = (item) => {
    const { dispatch, currentUser } = this.props;
    const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
    dispatch({
      type: 'waitingLearningIssue/dcexport',
      payload: { qaId: item.sid, type: 2, targetId: this.state.zuid },
      callback: res => {
        if (res.code == 200) {
          this.setState({ showModel1: false });
          this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
        }
      },
    });
  }

  setClassName = (record, index) => {
    return (index < this.state.aALeng ? styles.red : '');
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const columns1 = [
      {
        title: '问题',
        dataIndex: 'question'
      },
      {
        title: '分类',
        dataIndex: 'category'
      },
      {
        title: '操作',
        render: (text, item) => {
          return <div className={styles.pb}>
            <div className={styles.buttongl} onClick={(text) => { this.handleDelete(item) }}>
              <span><Icon size="small" type="link" style={{ marginRight: 5 }} /></span>
              <span>关联</span>
            </div>
          </div>
        }
      },
    ];

    return (
      <Suspense fallback={<PageLoading />}>
        <div style={{ padding: '0px 20px 0px 30px' }}>
          <div style={{ marginBottom: 20 }} className={styles.fromColumn}>
            <div>
              <Form className={styles.buttonA} layout="inline">
                <FormItem>
                  <RangePicker
                    onChange={this.onChange}
                    style={{ width: 220 }}
                    defaultValue={[
                      moment(this.state.beginTime, dateFormat),
                      moment(this.state.overTime, dateFormat),
                    ]}
                    format={dateFormat}
                  />
                </FormItem>
                <FormItem>
                  {getFieldDecorator('lose', { initialValue: this.state.electb, })(
                    <Select style={{ width: 130 }}>
                      <Option value='false'>未忽略</Option>
                      <Option value='true'>已忽略</Option>
                    </Select>
                  )}
                </FormItem>
                <FormItem>
                  {getFieldDecorator('seek', { initialValue: '', })(
                    <Input
                      placeholder="请输入搜索内容"
                      onPressEnter={this.handleSubmit}
                    />
                  )}
                </FormItem>
                <FormItem className='buttonYs'>
                  <Button onClick={this.handleSubmit} icon="search">搜索</Button>
                </FormItem>
              </Form>
            </div>
            <span style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
              <span className="buttonYs">
                <Button onClick={this.down} icon="arrow-down">下载</Button>
              </span>
              {this.state.electb === 'false' ? (
                <span className='zdyButtonA'>
                  <Button onClick={this.handleRelete} type='primary' icon="eye-invisible">批量忽略</Button>
                </span>
              ) : (
                <span className='zdyButtonA'>
                  <Button onClick={this.handleRelete} type='primary' icon="eye-invisible">批量恢复</Button>
                </span>
              )}
            </span>
          </div>
          {this.lessdata()}
          <Modal
            style={{ top: 60 }}
            width={'calc( 70vw)'}
            className={styles.overa}
            title='添加关联知识点'
            visible={this.state.showModel1}
            footer={null}
            onCancel={() => {
              this.setState({ showModel1: false })
            }}
            onOk={() => { // 确定方法不开出去
              this.setState({ showModel1: false })
            }}
          >
            <Form layout="inline" style={{ paddingBottom: 20 }}>
              <FormItem style={{ marginLeft: 20 }}>
                <Select defaultValue={this.state.numberRadio} style={{ width: 160 }} onChange={this.onFromA}>
                  <Option value='1'>搜索问题</Option>
                  <Option value='2'>搜索答案</Option>
                </Select>
              </FormItem>
              <FormItem >
                {getFieldDecorator('businessName', { initialValue: '', })(
                  <Search placeholder="请输入搜索内容" onSearch={value => this.onFrom(value)} style={{ width: 320 }} />
                )}
              </FormItem>
            </Form>
            <Spin spinning={this.state.logins}>
              <Table
                rowClassName={this.setClassName}
                className={styles.over}
                // bordered
                columns={columns1}
                dataSource={this.state.qaListTable}
                pagination={{  // 分页
                  total: this.state.total2, // 数据总数量
                  pageSizeOptions: [15, 30, 50, 100],
                  pageSize: this.state.glLeng,  // 显示几条一页
                  current: this.state.pagetwo, // 当前页
                  showQuickJumper: true,
                  onChange: this.handleSubmitComment,
                  // onShowSizeChange: this.handleSubmitComments
                }}
              />
            </Spin>
          </Modal>
          <Drawer
            title={<FormattedMessage id="app.overView.editQa" />}
            placement="right"
            closable
            onClose={this.onClose}
            visible={this.state.close}
            width={800}
            destroyOnClose
          >
            <EditQa questions={this.state.qaId} onClose={this.onClose} />
          </Drawer>
        </div>
      </Suspense>
    );
  }

  handleChange = (pagination, filters, sorter) => {
    if (sorter.columnKey === 'count') {
      if (sorter.order === "ascend") { // 升序
        this.setState({ order: 'count', asc: 'asc' })
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'count', 'asc')
      };
      if (sorter.order === "descend") { // 降序
        this.setState({ order: 'count', asc: 'desc' })
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'count', 'desc')
      };
      this.setState({ sortOrder: sorter.order, evaluate: 'count' })
    };
    if (sorter.columnKey === 'time') {
      if (sorter.order === "ascend") { // 升序
        this.setState({ order: 'updateTime', asc: 'asc' })
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'updateTime', 'asc')
      };
      if (sorter.order === "descend") { // 降序
        this.setState({ order: 'updateTime', asc: 'desc' })
        this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'updateTime', 'desc')
      };
      this.setState({ sortOrder: sorter.order, evaluate: 'count' })
    }
  }

  lessdata = () => {
    const { selectedRowKeys } = this.state
    // 多选
    const rowCheckSelection = {
      type: 'checkbox',
      selectedRowKeys, //告诉插件我们点击的哪一行
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys, selectedRows: selectedRows })
      }
    }
    const columns = [
      {
        title: `转人工问题`,
        width: 'calc(20vw)',
        dataIndex: 'question',
        render(item) {
          return (
            // <div className={styles.wtbj}>{item}</div>
            <div className={styles.wtbj} dangerouslySetInnerHTML={{ __html: item }}></div>
          )
        }
      },
      {
        title: '询问次数',
        width: 'calc(15vw)',
        dataIndex: 'count',
        sorter: (a, b) => { },
        // sortOrder:this.state.sortOrder
      },
      {
        title: '转人工时间',
        width: 'calc(20vw)',
        dataIndex: 'time',
        sorter: (a, b) => { },
        // sorter: (a, b) => a.createTime - b.createTime,
        render: (dataIndex) => {
          return moment(dataIndex).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      {
        title: '操作',
        width: 'calc(18vw)',
        render: (text, row) => {
          return <div className={styles.wt}>
            <div className='zdyButtonA'>
              <Button type='primary' icon='link' size="small" onClick={() => this.handleOpen(row)}>
                关联
              </Button>
            </div>
            <div className='zdyButtonA'>
              <Button type="primary" size='small' icon="plus" className={styles.processBtn} onClick={() => this.newlyAdded(row)}>
                新增
              </Button>
            </div>
            {
              this.state.electb === 'false' ? <div className='zdyButtonA'>
                <Button type="primary" icon="eye-invisible" size='small' className={styles.processBtn} onClick={() => this.ignore(row)}>忽略</Button>
              </div> : ''
            }
            <UpDownCharacter
              text={text}
              name='上下文'
              icons='bars'
              title='聊天上下文'
              updowndate={this.state.upDownDate}
              onSubmitA={this.handleSubUpDwonDate}
              loginjqr={this.state.loginjqr}
              empty={this.empty}
            />
            {
              this.state.electb === 'false' ? '' : <div className='zdyButtonA'>
                <Button type="primary" size='small' className={styles.processBtn} onClick={() => this.recovery(row)}>
                  <MyIcon type="icon-huifu" />恢复
                </Button>
              </div>
            }
          </div>;
        },
      }
    ];

    return (
      <Spin spinning={this.state.login}>
        <Table
          className='zdyTable'
          rowSelection={rowCheckSelection}
          style={{ padding: '0px 30px 0px 30px' }}
          columns={columns}
          dataSource={this.state.dataSource}//数据
          onChange={this.handleChange}
          pagination={{  // 分页
            total: this.state.total,
            pageSize: this.state.pageSize,  // 显示几条一页
            pageSizeOptions: ['15', '30', '50', '100'],
            current: this.state.page, // 当前页
            showSizeChanger: true,  // 是否显示可以设置几条一页的选项
            showQuickJumper: true,
            onChange: this.onChangeA,
            onShowSizeChange: this.onShowSizeChangeA
          }}
        />
      </Spin>
    )
  }

  onChangeA = (val) => { // 页数选择
    this.setState({ page: val });
    setTimeout(() => {
      const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
      this.fetch(seek, this.state.break, beginTime, overTime, val, pageSize, order, asc);
    }, 1)
  }

  // 每页显示多少条数据
  onShowSizeChangeA = (current, pageSize) => {
    this.setState({ pageSize: pageSize, page: current });
    const { seek, beginTime, overTime, page, order, asc } = this.state;
    this.fetch(seek, this.state.break, beginTime, overTime, current, pageSize, order, asc);
  }

  handleRelete = () => {
    let rows = this.state.selectedRows;
    if (this.state.break === false) { // 忽略
      if (rows) {
        let its = [];
        rows.map((item) => {
          its.push(item.id)
        });
        Modal['confirm']({
          title: '忽略问题',
          content: '确定忽略吗？',
          okText: "确认",
          cancelText: "取消",
          onOk: () => {
            const { dispatch } = this.props;
            this.reqRef = requestAnimationFrame(() => {
              dispatch({
                type: 'waitingLearningIssue/fetchk',
                payload: { ids: its, ignored: this.state.portJudge },
                callback: res => {
                  if (res.code == 200) {
                    message['success'](`${res.msg}`)
                    setTimeout(() => {
                      const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
                      this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
                    }, 1)
                  };
                  if (res.code === 1) {
                    message['error'](`${res.msg}`);
                  }
                },
              });
            });
          },
          onCancel() {

          }
        })
      } else {
        message['error']('您还没有选择！');
      }
    } else if (this.state.break === true) {
      if (rows) {
        let its = [];
        rows.map((item) => {
          its.push(item.id)
        });
        const { dispatch } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'waitingLearningIssue/fetchk',
            payload: { ids: its, ignored: this.state.portJudge },
            callback: res => {
              if (res.code == 200) {
                message['success'](`${res.msg}`);
                setTimeout(() => {
                  const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
                  this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
                }, 1)
              };
              if (res.code === 1) {
                message['error'](`${res.msg}`);
              }
            },
          });
        });
      } else {
        message['error']('您还没有选择！');
      }
    }
  }

  empty = () => {
    this.setState({ upDownDate: [] });
  }

  //  关联方法
  handleOpen = (row) => {
    this.props.form.setFields({ "businessName": "" });
    this.setState({ question: row.question, query: '' }, () => {
      this.AnswerRelevance(this.state.question, this.state.field, this.state.query, 1, 10);
      this.setState({ showModel1: true, zuid: row.id });
    })
  }
}
export default connect(({ user }) => ({ // 全局数据 portJudge
  currentUser: user.currentUser,
}))(Form.create()(UnknownProblem));
